import React, { useState, useEffect } from 'react';
import { Button, Divider } from 'antd';
import { useHistory } from 'react-router-dom';
import { LoadingOutlined } from '@ant-design/icons';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  combile_mxdata_mxcol_util,
  use_olreport_bybbbm,
  use_dict_byzdmc
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import Qtck_mx_hook  from './qtck_mx_hook.js';
import { use_qtck_initformdata, use_qtck_mx_column_initformdata } from './use_kc_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';

const Qtck_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    dict_dw:[],
    datas_ckck: [],
    datas_wlmc: [],
    datas_kh:[],
    datas_bm:[],
    datas_ry:[],
    datas_djzt:[],
    datas_llry:[],
    query_gys:[]
    
  })
  /**mxdata:明细数据 delidarr:明细删除id集合 mxcolumn：明细列配置项*/
  const [formdata, setformdata] = useState(use_qtck_initformdata)
  const [mxdata, setmxdata] = useState([])
  const [delidarr, setdelidarr] = useState([]);
  const [mxcolums, setmxcolums]=useState(use_qtck_mx_column_initformdata)
  const [isloading, setisloading] = useState(true)
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();

/**强制刷新明细表 用于特殊场景*/
  const [switche, setswitche] = useState(true);
  const forceupdate = () => {setswitche(false)}
  useEffect(() => {switche?"1":setswitche(true)}, [switche])

/**
 * 根据主表数据加载表单和明细
 * @param {*} id */
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/kcgl/query_qtck_byid", 'POST', { id }, "json")
    let formdatares = rtdata.resultdata.formdata;
    let mxdatares = rtdata.resultdata.mxdata;
    var newformdata = resultdata_to_formdata(formdatares, formdata);
    var newmxdata = addkey_for_mxdata(mxdatares)
    setformdata(newformdata);
    setmxdata(newmxdata);
    await initdatasource()
  }

  // 页面进入加载数据 根据 edit加载表单数据 或者取消loading动画
  useEffect(() => {
    JSON.parse(storage.pre_qtck_item).type == "edit" ? loadformdata(JSON.parse(storage.pre_qtck_item).data.id) :  initdatasource()
  }, [])

   /**初始化数据仓库*/
   const initdatasource = async () => {
    const cusqueryobj = await use_olreport_bybbbm(['query_gys','query_ry', 'query_bm', 'query_kh', 'query_wl_qtck', 'query_ck','query_ry_ll',]);
    const dictobj = await use_dict_byzdmc(['dict_djzt']);

    Object.assign(dynDatasObject, {
      datas_wlmc: cusqueryobj.query_wl_qtck,
      datas_ckck: cusqueryobj.query_ck,
      datas_ry: cusqueryobj.query_ry, 
      datas_bm: cusqueryobj.query_bm,
      datas_kh: cusqueryobj.query_kh,
      datas_djzt: dictobj.dict_djzt,
      query_gys: cusqueryobj.query_gys,
      datas_llry:cusqueryobj.query_ry_ll,
    });

    setdynDatasObject({ ...dynDatasObject });
    setisloading(false);
  }

    //设置value  根据业务场景自己定义
    const setfield = (onekey, value, settype) => {
      if (settype == 'single') {
        var newitem = formdata[onekey]
        newitem.value = value
        let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
        setformdata(newformdata)
      } else if (settype == "muti") {
        var tansferarr = onekey;
        var selectrow = value;
        var newformdata = {}
        tansferarr.forEach(item => {
          var newitem = formdata[item.target]
          newitem.value = selectrow ? selectrow[item.origin] : ""
          newformdata = Object.assign({}, formdata, { [item.target]: newitem });
        })
        setformdata(newformdata)
      }
  
    }

    //提交方法
  const handleupload = async () => {

    var checkobj = checkdatavalid_util_formdata(formdata)
    
    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage);return; }
    else;
//拼接明细
    var newmxdatalist = combile_mxdata_mxcol_util(mxdata, mxcolums)
    var uploadurl = "";
    if (JSON.parse(storage.pre_qtck_item).type == "add") {
      uploadurl = "/admin/kcgl/add_qtck"
    } else if (JSON.parse(storage.pre_qtck_item).type == "edit") {
      uploadurl = "/admin/kcgl/update_qtck"
    } else;

    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata, mxdata: newmxdatalist, delidarr: delidarr, storage: storage }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
    var newmxdata = addkey_for_mxdata(rtdata.resultdata.mxdata)
    setmxdata(newmxdata);
    setdelidarr([])
    dropByCacheKey("qtck_form")
    dropByCacheKey("qtck_list")
    setnowroute({route:"/shipSRM/kcgl/qtck_list",title:"其他出库",closeroute:"/shipSRM/kcgl/qtck_form"})

  }

  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    formdataarr.sort((a, b) => parseInt(a.xuhao) - parseInt(b.xuhao));
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
        dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    })
    return renderstr
  }

  return (
    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%",   color: "white", fontSize: "0.8rem",
      position:"absolute",
      }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <Button type="primary" onClick={handleupload}
          style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem" }}>
          <SaveOutlined />{JSON.parse(storage.pre_qtck_item).type == "add" ? "保存" : "修改"}</Button>
        {/* 主表区域结束 */}
        <Divider></Divider>

     {/* 明细表 */}
        <div style={styles.linestyle}>
          <div style={styles.lineleft}><span style={{ color: "grey" }}>&nbsp;物料明细</span></div>
        </div>
        {isloading ?
          (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
          :
          <div style={{ position: "relative",  width: "100%", overflowX: "auto",paddingLeft:"2%" ,}}>
            {switche && <Qtck_mx_hook colmuns={mxcolums} datasource={mxdata}
              onepageheight="10vh"
              styleobj={{ width: collapsed?"120vw":"110vw", height: "70%" }}
              dynDatasObject={dynDatasObject}
              formdata={formdata}
              handledelid={ids => { ids.length !== 0 ? setdelidarr([...delidarr, ...ids]) : ''; }}
              handgetmxdata={(tabledata) => {
                addkey_for_mxdata(tabledata)
                setmxdata(tabledata)
              }}
              forceupdate={forceupdate}
            />}</div>
        }
      </div>
    </div>
  )
}

export default Qtck_form

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
    topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft:"1vw",paddingRight:"1vw",height: "2vw", 
    position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" 
  },
  butmainstyle: {paddingLeft:"1vw", height: "2vw", position: "absolute", 
    right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" 
  },
  butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", 
    position: "absolute", right: "12%", top: "0%",fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw"
  },
  kshcontainer: {
    width: "98%", height: "95%", position: "absolute", top: "3%", left: "1%", backgroundColor: "white", color: "black",
    borderRadius: "10px",overflowY:"scroll"
  },
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", 
    fontSize: "0.6rem", fontWeight: "700",color: "#a91f24",textIndent:"2rem" },
}